package com.soft.mainsite.component.beetl.tag.content;

import cn.hutool.core.convert.Convert;
import com.github.pagehelper.PageInfo;
import com.soft.mainsite.common.constant.CmsConst;
import com.soft.mainsite.common.exception.CmsException;
import com.soft.mainsite.common.exception.SystemException;
import com.soft.mainsite.common.utils.CmsUtil;
import com.soft.mainsite.module.publishlog.service.PublishLogService;
import com.soft.mainsite.module.web.cms.service.CategoryService;
import com.soft.mainsite.module.web.cms.service.ContentService;
import com.soft.mainsite.module.web.cms.service.SiteService;
import com.soft.mainsite.mybatis.model.TCmsCategory;
import com.soft.mainsite.mybatis.model.TCmsSite;
import lombok.extern.slf4j.Slf4j;
import org.beetl.core.GeneralVarTagBinding;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * Description:栏目内容列表标签
 *
 * @author liupengtao
 * @create 2019/05/05
 **/
@Slf4j
@Service
@Scope("prototype")
public class RecommendContentListTag extends GeneralVarTagBinding {

    @Autowired
    private ContentService contentService;

    @Autowired
    private SiteService siteService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private PublishLogService publishLogService;

    @Value("${system.site.subfix}")
    private String siteSubfix;

    @Value("${system.site.prefix}")
    private String sitePrefix;


    /**
     * 文章列表标签
     * <p>
     * siteId:站点id
     * categoryId:分类编号
     * hasChild：是否包含子栏目内容
     * isHot：热门
     * titleLen:标题长度
     * target:是否新窗口打开
     * orderBy:排序
     * size:调用条数
     * recommend:是否推荐 ：0为不推荐，1为推荐
     */
    @Override
    public void render() {

        if (CmsUtil.isNullOrEmpty(this.args[1])) {
            throw new SystemException("标签参数不能为空！");
        }

        Integer isPub = CmsUtil.isNullOrEmpty(this.getAttributeValue("isPub")) ? 0 : Convert.toInt(this.getAttributeValue("isPub"));
        Integer titleLen = Convert.toInt(this.getAttributeValue("titleLen"));
        String siteType = Convert.toStr(this.getAttributeValue("siteType"));
        Integer siteId = Convert.toInt(this.getAttributeValue("siteId"));
        boolean isStatic = Convert.toBool(this.getAttributeValue("isStatic"));
        Long categoryId = Convert.toLong(this.getAttributeValue("categoryId"));
        Integer topicId = Convert.toInt(this.getAttributeValue("topicId"));
        Integer isRecommend = CmsUtil.isNullOrEmpty(this.getAttributeValue("isRecommend")) ? 0 : Convert.toInt(this.getAttributeValue("isRecommend"));
        Integer orderBy = Convert.toInt(this.getAttributeValue("orderBy"));
        Integer pageSize = Integer.parseInt((String) this.getAttributeValue("size"));
        Integer pubPageSize = Convert.toInt(this.getAttributeValue("pubSize"));

        if (CmsUtil.isNullOrEmpty(this.getAttributeValue(CmsConst.PARAM_PUBSIZE))) {
            pubPageSize = pageSize;
        }

        PageInfo<Map> pageInfo = null;

        Long categoryIdCopy = categoryId;
        Integer siteIdCopy = siteId;

        if (CmsConst.RECOMMEND.equals(isRecommend)) {
            categoryIdCopy = null;
        }

        if (CmsConst.MAIN_SITE_TYPE.equals(siteType)) {
            siteType = null;
        }

        if (CmsConst.IS_PUB.equals(isPub)) {
            siteIdCopy = CmsConst.MAIN_SITE_ID;
            pageSize = pubPageSize;
        } else {
            siteType = null;
        }


        pageInfo = contentService.findHomeContentList(siteIdCopy, categoryIdCopy, topicId, orderBy, pageSize, siteType, isRecommend);

        if (CmsUtil.isNullOrEmpty(pageInfo.getList())) {
            return;
        }

        List<Map> mapList = pageInfo.getList();

        try {
            this.wrapRender(mapList, titleLen, siteId, isStatic);
        } catch (Exception e) {
            log.error("推荐栏目渲染失败", e);
        }

    }

    private void wrapRender(List<Map> contentList, int titleLen, int siteId, boolean isStatic) {
        HttpServletRequest request = (HttpServletRequest) ctx.getGlobal("request");
        String staticHtmlPath = ctx.getGlobal("staticHtmlPath") == null ? "" : (String) ctx.getGlobal("staticHtmlPath");
        int i = 1;
        for (Map content : contentList) {
            String title = content.get("title").toString();
            int length = title.length();
            if (length > titleLen) {
                content.put("title", title.substring(0, titleLen) + "...");
            }
            TCmsSite site = siteService.findById(siteId);

            if (CmsUtil.isNullOrEmpty(site)) {
                throw new CmsException("站点不存在[siteId:" + siteId + "]");
            }

            Long categoryId = Convert.toLong(content.get("category_id"));
            TCmsCategory category = categoryService.findById(categoryId);
            if (CmsUtil.isNullOrEmpty(category)) {
                throw new CmsException("栏目不存在[categoryId:" + category.getCategoryId() + "]");
            }
            String url = request.getContextPath() + staticHtmlPath + "/" + site.getSiteKey() + "/";
            url += category.getAlias() + "/" + content.get("content_id");

            if (isStatic && category.getCommon() && CmsConst.MAIN_SITE_ID.equals(Convert.toInt(content.get("site_id")))) {
                url = "/commonHtml/content/mobile/" + category.getAlias() + "/" + content.get("content_id");
            }

            content.put("url", url + siteSubfix);

            content.put("index", i);
            content.put("count", contentList.size());
            this.binds(content);
            this.doBodyRender();
            i++;

        }

    }

}
